<template>
  <div class="dashboard">
    <!-- 上方部分：动态数据展示和预征/入伍信息 -->
    <div class="top-section">
      <!-- 左上部分：方框展示区 -->
      <div class="top-left">
        <div>
          <h2>{{ boxTitle }}</h2>
          <di class="boxes">
            <div @click="handleToClub" class="box box-1" @mouseover="showTooltip('军事兴趣社团申请人数')"
              @mouseleave="hideTooltip">
              <span class="icon">社团申请人数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.preEnrollmentCount }}</span>
                <span class="unit">人</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/apply.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '军事兴趣社团申请人数'">
                军事兴趣类社团申请人数: {{ box.preEnrollmentCount }}
              </div>
            </div>

            <div @click="handleToTip" class="box box-2" @mouseover="showTooltip('发布通知数')" @mouseleave="hideTooltip">
              <span class="icon">发布通知数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.notificationCount }}</span>
                <span class="unit">条</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/notice.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '发布通知数'">
                发布通知数: {{ box.notificationCount }}
              </div>
            </div>
          </di>

          <div class="boxes">
            <div @click="handleToPreReserve" class="box box-3" @mouseover="showTooltip('预储总人数')"
              @mouseleave="hideTooltip">
              <span class="icon">预储总人数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.totalReserveCount }}</span>
                <span class="unit">人</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/Army.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '预储总人数'">
                预储总人数: {{ box.totalReserveCount }}
              </div>
            </div>

            <div @click="handleToImg" class="box box-4" @mouseover="showTooltip('发布轮播图数')" @mouseleave="hideTooltip">
              <span class="icon">发布轮播图数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.carouselCount }}</span>
                <span class="unit">张</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/swipe.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '发布轮播图数'">
                发布轮播图数: {{ box.carouselCount }}
              </div>
            </div>
          </div>
          <div class="boxes">
            <div @click="handleToArmy" class="box box-5" @mouseover="showTooltip('入伍人数')" @mouseleave="hideTooltip">
              <span class="icon">入伍人数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.toArmyCount }}</span>
                <span class="unit">人</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/toArmy.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '入伍人数'">
                入伍人数: {{ box.toArmyCount }}
              </div>
            </div>
            <div class="box box-6" @mouseover="showTooltip('反馈人数')" @mouseleave="hideTooltip">
              <span class="icon">反馈数</span>
              <div class="count-content">
                <span class="highlight-number">{{ box.ideaBack }}</span>
                <span class="unit">条</span>
              </div>
              <div class="icon-circle">
                <img src="../assets/icons/ideaBack.svg" alt="icon" class="icon-img" />
              </div>
              <div class="tooltip" v-if="tooltipVisible && tooltipContent === '反馈人数'">
                反馈数: {{ box.ideaBack }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右上部分：折线图 -->
      <div class="top-right">
        <div class="chart-container">
          <h3 style="text-align: center;">军事兴趣社团/入伍信息</h3>
          <div class="chart-controls">
            <button :class="{ active: showPreEnrollment }" @click="toggleChartType('preEnrollment')">
              军事兴趣类社团
            </button>
            <button :class="{ active: showEnrollment }" @click="toggleChartType('enrollment')">
              应征入伍
            </button>
            <select v-model="selectedYearRange" @change="updateLineChart">
              <option value="1">今年</option>
              <option value="2">近2年</option>
              <option value="3">近3年</option>
              <option value="4">近4年</option>
              <option value="5">近5年</option>
              <option value="10">近10年</option>
            </select>
          </div>
          <div ref="lineChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 下方部分：柱状图和饼图 -->
    <div class="bottom">
      <!-- 柱状图 -->
      <div class="chart-container">
        <h3 style="text-align: center;">预储信息管理 - 年龄/身高/体重</h3>
        <div class="chart-controls">
          <select v-model="selectedBarCategory" @change="updateBarChart">
            <option value="age">年龄</option>
            <option value="height">身高</option>
            <option value="weight">体重</option>
          </select>
        </div>
        <div ref="barChart" class="chart"></div>
      </div>

      <!-- 饼图 -->
      <div class="chart-container">
        <h3 style="text-align: center;">预储信息管理 - 其他</h3>
        <div class="chart-controls">
          <select v-model="selectedPieCategory" @change="updatePieChart">
            <option value="college">学院</option>
            <option value="major">专业</option>
            <option value="gender">性别</option>
            <option value="politicalAffiliation">政治面貌</option>
            <option value="nationality">民族</option>
          </select>
        </div>
        <div ref="pieChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { getBarChartData, getBoxData, getLineChartData, getPieChartData } from '@/api/index/index'

const route = useRouter()

function handleToClub() {
  route.push('/admin/applyManage');
}

function handleToTip() {
  route.push('/Mmp/notice');
}

function handleToPreReserve() {
  route.push('/admin/preReserve/memberManage');
}

function handleToImg() {
  route.push('/Mmp/swiper');
}

function handleToArmy() {
  route.push('/admin/JoinArmy/joinArmyMember');
}

// 方框展示区相关
const boxTitle = ref<string>('动态数据展示');
const box = ref({
  preEnrollmentCount: 0, // 军事兴趣社团申请人数
  notificationCount: 0, // 发布通知数
  totalReserveCount: 0, // 预储总人数
  carouselCount: 0, // 发布轮播图数
  toArmyCount: 0, // 入伍人数
  ideaBack: 0, // 反馈数
});
// 请求方框数据和图表数据
const fetchDashboardData = async () => {
  try {
    const response = await getBoxData();
    const data = response.data;
    // 更新方框数据
    box.value.preEnrollmentCount = data.preEnrollmentCount;
    box.value.notificationCount = data.notificationCount;
    box.value.totalReserveCount = data.totalReserveCount;
    box.value.carouselCount = data.carouselCount;
    box.value.toArmyCount = data.toArmyCount; //入伍人数
    box.value.ideaBack = data.ideaBack;// 反馈数
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};
const tooltipVisible = ref<boolean>(false);
const tooltipContent = ref<string>('');

// 折线图相关
const lineChart = ref<HTMLElement | null>(null);
const selectedYearRange = ref<string>('1');
const showPreEnrollment = ref<boolean>(true);
const showEnrollment = ref<boolean>(true);

// 柱状图相关
const barChart = ref<HTMLElement | null>(null);
const selectedBarCategory = ref<string>('age');

// 饼图相关
const pieChart = ref<HTMLElement | null>(null);
const selectedPieCategory = ref<string>('college');

// 初始化折线图
let lineChartInstance: echarts.ECharts | null = null;
let lineChartObserver: ResizeObserver | null = null;
const initLineChart = () => {
  if (lineChart.value) {
    lineChartInstance = echarts.init(lineChart.value);
    updateLineChart();

    // 监听父容器尺寸变化
    lineChartObserver = new ResizeObserver(() => {
      lineChartInstance?.resize();
    });
    lineChartObserver.observe(lineChart.value);
  }
};

// 更新折线图数据
const updateLineChart = async () => {
  try {
    const params = { yearRange: selectedYearRange.value };
    const response = await getLineChartData(params);
    const data = response.data;
    const option = {
      xAxis: {
        type: 'category',
        data: data.xaxisData,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '军事兴趣社团',
          data: showPreEnrollment.value ? data.preEnrollmentData : [],
          type: 'line',
          smooth: true,
          areaStyle: {
            color: 'rgba(75, 192, 192, 0.2)',
          },
        },
        {
          name: '应征入伍',
          data: showEnrollment.value ? data.enrollmentData : [],
          type: 'line',
          smooth: true,
          areaStyle: {
            color: 'rgba(153, 102, 255, 0.2)',
          },
        },
      ],
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['军事兴趣社团', '应征入伍'],
      },
    };
    lineChartInstance?.setOption(option);
  } catch (error) {
    console.error("获取折线图数据失败:", error);
  }
};

// 初始化柱状图
let barChartInstance: echarts.ECharts | null = null;
let barChartObserver: ResizeObserver | null = null;
const initBarChart = () => {
  if (barChart.value) {
    barChartInstance = echarts.init(barChart.value);
    updateBarChart();
    // 监听父容器尺寸变化
    barChartObserver = new ResizeObserver(() => {
      barChartInstance?.resize();
    });
    barChartObserver.observe(barChart.value);
  }
};

const colors = [
  '#FF6B6B', // 红色
  '#FFD93D', // 黄色
  '#6BCB77', // 绿色
  '#4D96FF', // 蓝色
  '#9D4EDD', // 紫色
  '#FF9F1C', // 橙色
  '#3A86FF', // 深蓝
  '#FF006E', // 粉红
  '#8338EC', // 深紫
  '#FB5607', // 深橙
  '#FFBE0B', // 明黄
  '#00F5D4', // 青绿
  '#007F5F', // 深绿
  '#2B2D42', // 深灰
  '#EF233C', // 鲜红
  '#8D99AE', // 灰蓝
  '#FFD6A5', // 浅橙
  '#C084FC', // 浅紫
  '#4CC9F0', // 浅蓝
  '#FF66B3'  // 浅粉
];
//更新柱状图数据
const updateBarChart = async () => {
  try {
    const params = { category: selectedBarCategory.value };
    const response = await getBarChartData(params);
    const data = response.data;

    // 为每个柱子添加不同的颜色
    const seriesData = data.values.map((value, index) => ({
      value,
      itemStyle: { color: colors[index % colors.length] } // 循环使用颜色
    }));

    const option = {
      xAxis: {
        type: 'category',
        data: data.categories,
      },
      yAxis: {
        type: 'value',
        name: "人数/人",
        nameGap: 10,
      },
      series: [
        {
          data: seriesData,
          type: 'bar',
        },
      ],
      tooltip: {
        trigger: 'axis',
      },
    };
    barChartInstance?.setOption(option);
  } catch (error) {
    console.error("获取柱状图数据失败:", error);
  }
};

// 初始化饼图
let pieChartInstance: echarts.ECharts | null = null;
let pieChartObserver: ResizeObserver | null = null;
const initPieChart = () => {
  if (pieChart.value) {
    pieChartInstance = echarts.init(pieChart.value);
    updatePieChart();
    // 监听父容器尺寸变化
    pieChartObserver = new ResizeObserver(() => {
      pieChartInstance?.resize();
    });
    pieChartObserver.observe(pieChart.value);
  }
};

// 更新饼图数据
const updatePieChart = async () => {
  try {
    const params = { category: selectedPieCategory.value };
    const response = await getPieChartData(params);
    const data = response.data;
    const option = {
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          type: 'pie',
          data: data,
        },
      ],
    };
    pieChartInstance?.setOption(option);
  } catch (error) {
    console.error("获取饼图数据失败:", error);
  }
};

// 切换折线图显示
const toggleChartType = (type: string) => {
  if (type === 'preEnrollment') {
    showPreEnrollment.value = !showPreEnrollment.value;
  } else if (type === 'enrollment') {
    showEnrollment.value = !showEnrollment.value;
  }
  updateLineChart();
};

// 方框展示区的交互
const showTooltip = (content: string) => {
  tooltipContent.value = content;
  tooltipVisible.value = true;
};

const hideTooltip = () => {
  tooltipVisible.value = false;
};

// 在组件卸载时取消监听
onUnmounted(() => {
  if (lineChartObserver) {
    lineChartObserver.disconnect();
  }
  if (barChartObserver) {
    barChartObserver.disconnect();
  }
  if (pieChartObserver) {
    pieChartObserver.disconnect();
  }
});

// 生命周期钩子
onMounted(() => {
  fetchDashboardData(); // 获取初始数据
  initLineChart();
  initBarChart();
  initPieChart();
});
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.dashboard {
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.top-section {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.top-left {
  flex: 2;
  min-width: 30rem;
  background-color: #f9f9f9;
  box-shadow: 0 0.2rem 0.8rem rgba(0, 0, 0, 0.1);
  padding: 1rem;
  border-radius: 0.8rem;
}

.top-right {
  flex: 3;
  min-width: 30rem;
}

.bottom {
  display: flex;
  gap: 1rem;
  flex-wrap: nowrap;
  /* 强制不换行，确保柱状图和饼图始终在一行 */
  justify-content: space-between;
  /* 均匀分布空间 */
}

.box-container {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.boxes {
  justify-content: center;
  margin-top: 1rem;
  display: flex;
  gap: 1rem;
  flex-wrap: nowrap;
  /* 禁止换行 */
  justify-content: space-between;
  /* 均匀分布 */
}

.box {
  padding: 1rem;
  border: 0.1rem solid #ccc;
  border-radius: 0.8rem;
  cursor: pointer;
  position: relative;
  flex: 1 1 calc(50% - 10px);
  text-align: center;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 6.1rem;
}

.count-content {
  text-align: center;
}

.highlight-number {
  font-size: 2.8rem;
  font-weight: 700;
  color: #f03e3e;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  margin-right: 0.5rem;
}

.unit {
  font-size: 1.2rem;
  color: #868e96;
  vertical-align: super;
}

.icon {
  font-size: 1.3rem;
}

.icon-circle {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 3.2rem;
  height: 3.2rem;
  background-color: #7e1c1c;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: translate(25%, 25%);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.icon-img {
  width: 1.5rem;
  height: 1.5rem;
  filter: brightness(0) invert(1);
}

.tooltip {
  position: absolute;
  top: -2rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: #333;
  color: #fff;
  padding: 0.5rem;
  border-radius: 0.4rem;
  font-size: 0.8rem;
}

.chart-container {
  flex: 1;
  /* 平均分配宽度 */
  background-color: #f9f9f9;
  padding: 1rem;
  border-radius: 0.8rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 0;
  /* 防止 flex 项溢出 */
  aspect-ratio: 17 / 8;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.chart-controls {
  display: flex;
  gap: 0.8rem;
  justify-content: flex-start;
}

.chart-controls button {
  padding: 0.35rem 0.08rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: #e0e0e0;
  font-size: 12px;
}

.chart-controls button.active {
  background-color: #007bff;
  color: #fff;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 新增颜色变量 */
.box-1 {
  --box-bg: #E3F2FD;
  --box-color: #2196F3;
}

.box-2 {
  --box-bg: #E8F5E9;
  --box-color: #4CAF50;
}

.box-3 {
  --box-bg: #FFF3E0;
  --box-color: #FF9800;
}

.box-4 {
  --box-bg: #F3E5F5;
  --box-color: #9C27B0;
}

.box-5 {
  --box-bg: #FFEBEE;
  --box-color: #F44336;
}

.box-6 {
  --box-bg: #E0F7FA;
  --box-color: #00BCD4;
}

.box {
  background-color: var(--box-bg);
  border: 1px solid rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: visible;
}

.box:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 2;
}

.icon,
.highlight-number {
  color: var(--box-color);
  transition: color 0.3s ease;
}

.icon-circle {
  background-color: var(--box-color);
  transition: background-color 0.3s ease;
}

/* 优化工具提示 */
.tooltip {
  background-color: rgba(0, 0, 0, 0.85);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  white-space: nowrap;
}

/* 调整图表容器层级 */
.chart {
  position: relative;
  z-index: 2;
}

/* 响应式设计，针对小屏幕 */
@media (max-width: 768px) {
  .bottom {
    flex-wrap: wrap;
    /* 小屏幕允许换行 */
  }
}
</style>